from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import UserService, RepositoryService, CollaboratorService
from common.result.Result import Result
from common.enum import BaseEnum
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time

async def GetRepositoryByShortUri(req: Request, shortUri: str):
    try:
        token = req.headers.get("token")
        if Str.isBlank(token, shortUri):
            Log.error('参数为空，检查参数')
            return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

        repository = await RepositoryService.getRepositoryByShortUri(shortUri)
        if repository == None:
            Log.error('repository 不存在')
            return Result.error(BaseEnum.REPOSITORY_NOT_EXISTS_ERROR)
        
        creatorId = repository.user_id
        creator = await UserService.getUserById(creatorId)
        if creator == None:
            Log.error('user 不存在')
            return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)

        # 构造 协作者 列表
        collaborators = await CollaboratorService.getListByRepositoryId(repository.id)
        userIds = [item.user_id for item in collaborators]
        userList = await UserService.getListByIds(userIds)

        result = dict(repository)
        result.update({
            "creator": {
                "username": creator.username,
                "avatar": creator.avatar
            },
            "collaborators": userList
        })

        return Result.success(result)
    except Exception as e:
        Log.error('创建知识库异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


